package com.clw.template.service.impl;

import com.clw.template.dto.UpdateRolePermission;
import com.clw.template.entity.SysRolePermissionRelation;
import com.clw.template.mapper.SysRolePermissionRelationMapper;
import com.clw.template.service.ISysRolePermissionRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户角色和权限关系表 服务实现类
 * </p>
 *
 * @author clw
 * @since 2019-11-01
 */
@Service
public class SysRolePermissionRelationServiceImpl extends ServiceImpl<SysRolePermissionRelationMapper, SysRolePermissionRelation> implements ISysRolePermissionRelationService {

    @Override
    public List<Long> getByRole(Long id) {
        List<SysRolePermissionRelation> list = this.lambdaQuery().eq(SysRolePermissionRelation::getRoleId, id).select(SysRolePermissionRelation::getPermissionId).list();
        List<Long> permissionIdList = new ArrayList<>();
        list.stream().forEach(sysRolePermissionRelation -> {
            permissionIdList.add(sysRolePermissionRelation.getPermissionId());
        });
        return permissionIdList;
    }

    @Override
    @Transactional
    public void updateByRole(UpdateRolePermission updateRolePermission) {
        this.lambdaUpdate().eq(SysRolePermissionRelation::getRoleId,updateRolePermission.getRoleId()).remove();
        List<SysRolePermissionRelation> sysRolePermissionRelationList = new ArrayList<>();
        updateRolePermission.getPermissionIds().stream().forEach(permissionId -> {
            SysRolePermissionRelation sysRolePermissionRelation = new SysRolePermissionRelation();
            sysRolePermissionRelation.setPermissionId(permissionId);
            sysRolePermissionRelation.setRoleId(updateRolePermission.getRoleId());
            sysRolePermissionRelationList.add(sysRolePermissionRelation);
        });
        saveBatch(sysRolePermissionRelationList);
    }
}
